//
//  YWGenerateQRCodeController.m
//  YWPhotoEditMaster
//
//  Created by jun peng on 2023/9/6.
//

#import "YWGenerateQRCodeController.h"
#import <CoreImage/CoreImage.h>

@interface YWGenerateQRCodeController ()
@property (weak, nonatomic) IBOutlet UIImageView *imageView;
@property (weak, nonatomic) IBOutlet UITextField *textField;

@end

@implementation YWGenerateQRCodeController

- (void)viewDidLoad {
    [super viewDidLoad];
    
}

-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    
    [self.view endEditing:YES];
    
    // 1.创建滤镜对象
    CIFilter *fiter = [CIFilter filterWithName:@"CIQRCodeGenerator"];
    
    // 2.设置相关属性
    [fiter setDefaults];
    
    // 3.设置输入数据
    NSString *inputData = self.textField.text ? self.textField.text : @"";
    NSData *data = [inputData dataUsingEncoding:NSUTF8StringEncoding];
    [fiter setValue:data forKeyPath:@"inputMessage"];
    
    // 3.2 设置二维码的纠错率
    [fiter setValue:@"M" forKey:@"inputCorrectionLevel"];
    
    // 4.获取输出结果
    CIImage *outputImage = [fiter outputImage];
    
    // 5.显示二维码
    CGAffineTransform transform = CGAffineTransformMakeScale(20, 20);
    CIImage *image = [outputImage imageByApplyingTransform:transform];
    
    UIImage *resultImage = [UIImage imageWithCIImage:image];
    NSLog(@"%@",NSStringFromCGSize(resultImage.size));
    
    //6.合并图片
    UIImage *centerImage = [UIImage imageNamed:@"平鼓"];
    
    self.imageView.image = [self getNewImageWithSourceImage:resultImage centerImage:centerImage];
    
}

-(UIImage *)getNewImageWithSourceImage:(UIImage *)sourceImage centerImage:(UIImage *)centerImage{
    
    CGSize size = sourceImage.size;
    
    //1.开启一个位图上下文
    UIGraphicsBeginImageContextWithOptions(size, NO, 0);
    [sourceImage drawInRect:CGRectMake(0, 0, size.width, size.height)];
    
    // 3. 绘制小图片
    CGFloat width = 80;
    CGFloat height = 80;
    CGFloat x = (size.width - width)*0.5;
    CGFloat y = (size.height - height)*0.5;
    
    [centerImage drawInRect:CGRectMake(x, y, width, height)];
    
    //3.从上下文当中取出一张图片
    UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
    
    //4.关闭上下文
    UIGraphicsEndImageContext();
    
    return  newImage;;
    
    
}

@end
